import { create } from 'zustand';

import { DialogueChartDataType, UserTrendsChartDataType, UserTrendsItemType } from '@/common';
import { AppStatusEnum, UserRoleEnum, AppType } from '@/common/app/constants';
import { agentSquareType, ConfigurationsInfo } from '@/common/types/app/app';
import { AppDetailType } from '@/types/app/type';

export interface HotQuestion {
  id: string;
  content: string;
  answer?: string;
}

export interface InputGuide {
  id: string;
  content: string;
}

interface OrchestrationState {
  showKeyAgent: boolean;
  showkeyHistory: boolean;
  showAgentHistory: boolean;
  fusionAgentSquare: agentSquareType[] | null;
  chatTitle: string;
  isLoadingAgentHistroy: boolean;
  userTrendsList: UserTrendsItemType[];
  userTrendsChartData: UserTrendsChartDataType[];
  dialogueList: UserTrendsItemType[];
  dialogueChartData: DialogueChartDataType[];
  userDislikeList: UserTrendsItemType[];

  appDetail: any;
  subAppDetail: any | null;
  appDetailInit: any | null;
  // 基础信息
  appName: string;
  tag: string;
  special_app_lable: string;
  isPublishTemplate: boolean;
  appDescription: string;
  appLogo: string;
  appLogoList: string[];
  sceneImage: string;
  sceneImageList: string[];
  createUserId: string;
  reviewStatus: AppStatusEnum;
  permissionConfig: any[];
  opening_remarks: string;
  task: string;
  role_setup: string;

  // 对话设置
  deepThinking: boolean;
  voiceEnabled: boolean;
  suggestedQuestions: boolean;
  inputGuide: boolean;
  tone: 'official' | 'neutral' | 'casual';
  responseLength: 'simple' | 'standard' | 'detailed';
  responseRigidity: 'strict' | 'moderate' | 'divergent';
  hotQuestions: HotQuestion[];
  hotQuestionsEnabled: boolean;
  inputGuides: InputGuide[];
  quote: boolean;
  internetSearch: boolean;

  // 知识库设置
  knowledgeBaseList: string[];
  datasetStats: {
    count: number;
    totalFiles: number;
    apiCount: number;
    appCount: number;
  };

  // 自定义配置项
  configurations: ConfigurationsInfo[];

  // 页面状态
  isInOrchestrationPage: boolean;

  // 用户权限
  userRole: UserRoleEnum | null;

  // 预览和分享相关
  isPreview: boolean;
  shareId: string | null;

  variables: Record<string, any>;
  userSelectVariables: Record<string, any>[];

  workflow: AppDetailType | undefined;

  fusionAppId: string | null;

  isDisableDataset: boolean;
  isEnableFunctionCalling: boolean;

  // 基础信息操作方法
  setAppName: (value: string) => void;
  setTag: (value: string) => void;
  setAppDescription: (value: string) => void;
  setAppLogo: (value: string) => void;
  setAppLogoList: (value: string[]) => void;
  setSceneImage: (value: string) => void;
  setSceneImageList: (value: string[]) => void;
  setCreateUserId: (value: string) => void;
  setReviewStatus: (value: AppStatusEnum) => void;
  setPermissionConfig: (value: any[]) => void;
  setOpeningRemarks: (value: string) => void;
  setTask: (value: string) => void;
  setRoleSetup: (value: string) => void;

  // 对话设置操作方法
  setDeepThinking: (value: boolean) => void;
  setVoiceEnabled: (value: boolean) => void;
  setSuggestedQuestions: (value: boolean) => void;
  setInputGuide: (value: boolean) => void;
  setTone: (value: 'official' | 'neutral' | 'casual') => void;
  setResponseLength: (value: 'simple' | 'standard' | 'detailed') => void;
  setResponseRigidity: (value: 'strict' | 'moderate' | 'divergent') => void;
  setHotQuestions: (value: HotQuestion[]) => void;
  setHotQuestionsEnabled: (value: boolean) => void;
  setInputGuides: (value: InputGuide[]) => void;
  setQuote: (value: boolean) => void;
  setInternetSearch: (value: boolean) => void;

  // 知识库操作方法
  setKnowledgeBaseList: (value: string[]) => void;
  addKnowledgeBase: (value: string) => void;
  removeKnowledgeBase: (value: string) => void;
  setIsPublishTemplate: (value: boolean) => void;
  setDatasetStats: (value: {
    count: number;
    totalFiles: number;
    apiCount: number;
    appCount: number;
  }) => void;

  // 配置项操作方法
  setConfigurations: (value: ConfigurationsInfo[]) => void;
  updateConfiguration: (name: string, value: string | number | boolean) => void;

  // 页面状态操作方法
  setIsInOrchestrationPage: (value: boolean) => void;

  // 应用详情设置方法
  setAppDetail: (appDetail: any) => void;
  setSubAppDetail: (subAppDetail: any | null) => void;
  setAppDetailInit: (value: any | null) => void;

  // 用户权限设置方法
  setUserRole: (roles: string[]) => void;

  // 预览和分享相关方法
  setIsPreview: (value: boolean) => void;
  setShareId: (id: string | null) => void;
  setVariables: (variables: Record<string, any>) => void;
  setUserSelectVariables: (variables: Record<string, any>[]) => void;
  setWorkflow: (workflow: AppDetailType) => void;

  setFusionAppId: (id: string | null) => void;

  setShowKeyAgent: (value: boolean) => void;
  setShowkeyHistory: (value: boolean) => void;
  setShowAgentHistory: (value: boolean) => void;
  setFusionAgentSquare: (value: agentSquareType[]) => void;
  setChatTitle: (value: string) => void;
  setIsLoadingAgentHistroy: (value: boolean) => void;
  setUserTrendsList: (value: any) => void;
  setUserTrendsChartData: (value: any) => void;
  setDialogueList: (value: any) => void;
  setDialogueChartData: (value: any) => void;
}

export const useOrchestrationStore = create<OrchestrationState>((set) => ({
  // 基础信息默认状态
  appName: '',
  tag: '',
  appDescription: '',
  appLogo: 'default',
  appLogoList: [],
  sceneImage: 'default',
  sceneImageList: [],
  createUserId: '',
  reviewStatus: AppStatusEnum.unpublished,
  permissionConfig: [],
  opening_remarks: '',
  task: '',
  role_setup: '',
  special_app_lable: '',
  isPublishTemplate: false,

  // 对话设置默认状态
  deepThinking: true,
  voiceEnabled: true,
  suggestedQuestions: true,
  inputGuide: false,
  tone: 'casual',
  responseLength: 'standard',
  responseRigidity: 'divergent',
  hotQuestions: [],
  hotQuestionsEnabled: true,
  inputGuides: [],
  quote: true,
  internetSearch: false,

  // 知识库默认状态
  knowledgeBaseList: [],
  datasetStats: {
    count: 0,
    totalFiles: 0,
    apiCount: 0,
    appCount: 0,
  },

  // 配置项默认状态
  configurations: [],

  // 页面状态默认值
  isInOrchestrationPage: false,

  // 用户权限默认状态
  userRole: null,

  // 预览和分享相关默认状态
  isPreview: false,
  shareId: null,

  variables: {},
  userSelectVariables: [],
  appDetail: {},
  subAppDetail: null,
  appDetailInit: null,

  workflow: undefined,

  fusionAppId: '',
  showKeyAgent: false, // 是否显示融合应用左侧
  showkeyHistory: false, // 是否显示融合应用右侧
  showAgentHistory: false,
  fusionAgentSquare: null,
  chatTitle: '',
  isLoadingAgentHistroy: false,
  userTrendsList: [{ title: '总用户' }, { title: '新增用户' }, { title: '重叠用户' }],
  userTrendsChartData: [],
  dialogueList: [{ title: '总用户' }, { title: '新增用户' }],
  userDislikeList: [
    { key: 'total', title: '问题数' },
    { key: 'processed', title: '已处理' },
    { key: 'unprocessed', title: '未处理' },
  ],
  dialogueChartData: [],

  isDisableDataset: false,
  isEnableFunctionCalling: false,

  // 应用看板
  setUserTrendsList: (value) => set({ userTrendsList: value }),
  setUserTrendsChartData: (value) => set({ userTrendsChartData: value }),
  setDialogueList: (value) => set({ dialogueList: value }),
  setDialogueChartData: (value) => set({ dialogueChartData: value }),

  setIsLoadingAgentHistroy: (value) => set({ isLoadingAgentHistroy: value }),
  setShowKeyAgent: (value) => set({ showKeyAgent: value }),
  setShowkeyHistory: (value) => set({ showkeyHistory: value }),
  setShowAgentHistory: (value) => set({ showAgentHistory: value }),
  setFusionAgentSquare: (value) => set({ fusionAgentSquare: value }),
  setChatTitle: (value) => set({ chatTitle: value }),
  // 基础信息设置方法
  setAppName: (value) => set({ appName: value }),
  setTag: (value) => set({ tag: value }),
  setCreateUserId: (value) => set({ createUserId: value }),
  setAppDescription: (value) => set({ appDescription: value }),
  setAppLogo: (value) => set({ appLogo: value }),
  setAppLogoList: (value) => set({ appLogoList: value }),
  setSceneImage: (value) => set({ sceneImage: value }),
  setSceneImageList: (value) => set({ sceneImageList: value }),
  setReviewStatus: (value) => set({ reviewStatus: value }),
  setPermissionConfig: (value) => set({ permissionConfig: value }),
  setOpeningRemarks: (value) => set({ opening_remarks: value }),
  setTask: (value) => set({ task: value }),
  setRoleSetup: (value) => set({ role_setup: value }),

  // 对话设置方法
  setDeepThinking: (value) => set({ deepThinking: value }),
  setVoiceEnabled: (value) => set({ voiceEnabled: value }),
  setSuggestedQuestions: (value) => set({ suggestedQuestions: value }),
  setInputGuide: (value) => set({ inputGuide: value }),
  setTone: (value) => set({ tone: value }),
  setResponseLength: (value) => set({ responseLength: value }),
  setResponseRigidity: (value) => set({ responseRigidity: value }),
  setHotQuestions: (value) => set({ hotQuestions: value }),
  setHotQuestionsEnabled: (value) => set({ hotQuestionsEnabled: value }),
  setInputGuides: (value) => set({ inputGuides: value }),
  setQuote: (value) => set({ quote: value }),
  setInternetSearch: (value) => set({ internetSearch: value }),
  setWorkflow: (workflow) => set({ workflow }),

  // 知识库设置方法
  setKnowledgeBaseList: (value) => set({ knowledgeBaseList: value }),
  addKnowledgeBase: (value) =>
    set((state) => ({
      knowledgeBaseList: [...state.knowledgeBaseList, value],
    })),
  removeKnowledgeBase: (value) =>
    set((state) => ({
      knowledgeBaseList: state.knowledgeBaseList.filter((item) => item !== value),
    })),
  setDatasetStats: (value) => set({ datasetStats: value }),

  setIsPublishTemplate: (value) => set({ isPublishTemplate: value }),

  // 配置项设置方法
  setConfigurations: (value) =>
    set((state) => {
      // alert('setConfigurations');
      // 获取所有已存在的配置项名称和对应的更新方法
      const existingConfigMap = {
        app_name: (value: any) => state.setAppName(value),
        tag: (value: any) => state.setTag(value),
        app_description: (value: any) => state.setAppDescription(value),
        app_logo: (value: any) => state.setAppLogo(value),
        scene_image: (value: any) => state.setSceneImage(value),
        create_user_id: (value: any) => state.setCreateUserId(value),
        review_status: (value: any) => state.setReviewStatus(value),
        permission_config: (value: any) => state.setPermissionConfig(value),
        deep_think: (value: any) => state.setDeepThinking(value),
        voice_enabled: (value: any) => state.setVoiceEnabled(value),
        guess_you_want2ask: (value: any) => state.setSuggestedQuestions(value),
        input_guide: (value: any) => state.setInputGuide(value),
        answer_tone: (value: any) => state.setTone(value),
        answer_strictness: (value: any) => state.setResponseRigidity(value),
        hot_questions: (value: any) => state.setHotQuestions(value),
        hot_questions_enabled: (value: any) => state.setHotQuestionsEnabled(value),
        input_guides: (value: any) => state.setInputGuides(value),
        knowledge_base_list: (value: any) => state.setKnowledgeBaseList(value),
        quote_enabled: (value: any) => state.setQuote(value),
        internet_search: (value: any) => state.setInternetSearch(value),
      };

      // 处理每个配置项
      value.forEach((config) => {
        const updateMethod = existingConfigMap[config.name as keyof typeof existingConfigMap];
        if (updateMethod) {
          // 如果配置项已存在，更新对应的值
          updateMethod(config.default_value);
        }
      });

      // 过滤掉已存在的配置项，只保留自定义配置项
      const filteredConfigurations = value.filter(
        (config) => !existingConfigMap[config.name as keyof typeof existingConfigMap],
      );

      console.log('filteredConfigurations', filteredConfigurations);

      // return { configurations:  []};
      return { configurations: filteredConfigurations };
    }),
  updateConfiguration: (name, value) =>
    set((state) => {
      const existingConfig = state.configurations.find((item) => item.name === name);

      if (existingConfig) {
        // 如果配置项存在，更新值
        return {
          configurations: state.configurations.map((item) =>
            item.name === name ? { ...item, default_value: value } : item,
          ),
        };
      }
      // 如果配置项不存在，新增配置项

      return {
        configurations: [...state.configurations, { name, default_value: value }],
      };
    }),

  // 页面状态设置方法
  setIsInOrchestrationPage: (value) => set({ isInOrchestrationPage: value }),

  setSubAppDetail: (subAppDetail) => set({ subAppDetail }),
  setAppDetailInit: (appDetailInit) => set({ appDetailInit }),

  setAppDetail: (appDetail) =>
    set({
      appDetail,
      userSelectVariables: appDetail.variables || [],
      appName: appDetail.app_name || '',
      special_app_lable: appDetail.special_app_lable || '',
      appDescription: appDetail.app_description || '',
      appLogo: appDetail.app_logo || 'default',
      sceneImage: appDetail.scene_image || '',
      createUserId: appDetail.create_user_id || '',
      reviewStatus: appDetail.review_status || AppStatusEnum.unpublished,
      permissionConfig: appDetail.permission_config || [],
      workflow: appDetail.workflow || undefined,
      configurations:
        appDetail.configurations?.map((config: ConfigurationsInfo) => {
          switch (config.name) {
            case 'app_name':
              return { ...config, default_value: appDetail.app_name || config.default_value };
            case 'tag':
              return { ...config, default_value: appDetail.tag || config.default_value };
            case 'app_description':
              return {
                ...config,
                default_value: appDetail.app_description || config.default_value,
              };
            case 'app_logo':
              return { ...config, default_value: appDetail.app_logo || config.default_value };
            case 'scene_image':
              return { ...config, default_value: appDetail.scene_image || config.default_value };
            // case 'permission_config':
            //   return { ...config, default_value: appDetail.permission_config || config.default_value };
            default:
              return config;
          }
        }) || [],
      isDisableDataset:
        appDetail.configurations?.find(
          (config: ConfigurationsInfo) => config.name === 'disable_dataset',
        )?.default_value === '1' || false,
      isEnableFunctionCalling:
        appDetail.appType == AppType.workflow ||
        appDetail.configurations?.find(
          (config: ConfigurationsInfo) => config.name === 'enable_function_calling',
        )?.default_value === '1' ||
        false,
    }),

  // 用户权限设置方法
  setUserRole: (roles) =>
    set(() => {
      // 定义权限等级
      const roleLevels = {
        admin: 3,
        knowledge_manager: 2,
        knowledge_reviewer: 1,
      };

      // 获取最高权限
      const highestRole = roles.reduce((maxRole, currentRole) => {
        const currentLevel = roleLevels[currentRole as keyof typeof roleLevels] || 0;
        const maxLevel = roleLevels[maxRole as keyof typeof roleLevels] || 0;
        return currentLevel > maxLevel ? currentRole : maxRole;
      }, '');

      return {
        userRole: highestRole as UserRoleEnum,
      };
      // return { userRole: 'admin' };
    }),

  // 预览和分享相关方法
  setIsPreview: (value) => set({ isPreview: value }),
  setShareId: (id) => set({ shareId: id }),
  setVariables: (variables) => set({ variables }),
  setUserSelectVariables: (variables) => set({ variables }),

  setFusionAppId(id) {
    set({ fusionAppId: id });
  },
}));
